package edu.gdut.tiantian.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import edu.gdut.tiantian.entity.Order;

@Repository
public interface OrderDao {
	//条件查询
	@Select("<script> select * from `order` where 1=1 "
			+ "<foreach collection='condition' index='keys' item='values'>"
			+ "<if test='keys == " +"\"orderId\" and keys != null" +"'>and orderId like CONCAT('%',#{values},'%')</if>"
			+ "<if test='keys == " +"\"status\" and keys != null and values!=-1" +"'>and status=#{values}</if>"
			+ "<if test='keys == " +"\"userId\" and keys != null" +"'>and userId like CONCAT('%',#{values},'%')</if>"
			+ "</foreach>"
			+ "</script>")
	@Results({
		@Result(id=true,property="orderId",column="orderId"),
		@Result(property = "category",column = "categoryId",one = @One(select="edu.gdut.tiantian.dao.CategoryDao.findById")),
		@Result(property="user",column="userId",one = @One(select="edu.gdut.tiantian.dao.UserDao.findById")),
		@Result(property="orderItems" , column="orderId",many = @Many(select="edu.gdut.tiantian.dao.OrderItemDao.getOrderItem"))
	})
	List<Order> findByCondition(@Param("condition")Map<String,String> condition);
	
	@Select("select * from `order` where userId=#{userId}")
	@Results({
		@Result(id=true,property="orderId",column="orderId"),
		@Result(property="orderItems" , column="orderId",many = @Many(select="edu.gdut.tiantian.dao.OrderItemDao.getOrderItem"))
	})
	List<Order> findByUserId(String userId);
	
	//修改订单状态
	@Update("update `order` set status=1 where orderId=#{orderId}")
	void updateStatus(String orderId);
	
	//添加订单
	@Insert("insert into `order`(orderId,recName,recPhone,recAddress,userId) values("
			+ "#{orderId},#{order.recName},#{order.recPhone},#{order.recAddress},#{userId})")
	void addOrder(@Param("order")Order order,@Param("userId")String userId,@Param("orderId")String orderId);
	
	//取消订单
	@Delete("delete from `order` where orderId=#{orderId}")
	void withdraw(String orderId);
	
	
	@Select("select * from `order` where orderId=#{orderId}")
	@Results({
		@Result(property="orderItems" , column="orderId",many = @Many(select="edu.gdut.tiantian.dao.OrderItemDao.getOrderItem")),
		@Result(property="user",column="userId",one = @One(select="edu.gdut.tiantian.dao.UserDao.findById"))
	})
	Order findByOrderId(String orderId);
	
}
